package com.yjw.demo.netty.bio;

import com.yjw.demo.netty.util.IoUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 服务端处理类
 *
 * @author yinjianwei
 * @date 2018/11/13
 */
public class ServerHandler implements Runnable {

    private Socket socket;

    public ServerHandler(Socket socket) {
        super();
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            pw = new PrintWriter(socket.getOutputStream(), true);
            while (true) {
                // 接收客户端的表达式消息
                String expression = null;
                if ((expression = br.readLine()) == null) {
                    break;
                }
                System.out.println("服务端收到消息：" + expression);
                // 计算表达式，返回计算机结果给客户端
                double result = calculate(expression);
                pw.println(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtils.close(br, pw, socket);
        }
    }

    /**
     * 计算客户端的表达式
     *
     * @param expression
     */
    private double calculate(String expression) {
        double result = 0;
        int index = 0;
        // 加
        if ((index = expression.indexOf("+")) != -1) {
            double one = Double.parseDouble(expression.substring(0, index).trim());
            double two = Double.parseDouble(expression.substring(index + 1, expression.length()).trim());
            result = one + two;
        }
        // 减
        if ((index = expression.indexOf("-")) != -1) {
            double one = Double.parseDouble(expression.substring(0, index).trim());
            double two = Double.parseDouble(expression.substring(index + 1, expression.length()).trim());
            result = one - two;
        }
        // 乘
        if ((index = expression.indexOf("*")) != -1) {
            double one = Double.parseDouble(expression.substring(0, index).trim());
            double two = Double.parseDouble(expression.substring(index + 1, expression.length()).trim());
            result = one * two;
        }
        // 除
        if ((index = expression.indexOf("/")) != -1) {
            double one = Double.parseDouble(expression.substring(0, index).trim());
            double two = Double.parseDouble(expression.substring(index + 1, expression.length()).trim());
            result = one / two;
        }
        return result;
    }
}